package com.yxsk.relay.job.admin.web.controller;

import com.yxsk.relay.job.admin.controller.JobAppController;
import com.yxsk.relay.job.admin.data.entity.BaseEntity;
import com.yxsk.relay.job.admin.data.entity.JobApps;
import com.yxsk.relay.job.admin.data.service.JobAppsService;
import com.yxsk.relay.job.admin.web.common.exception.RelayAdminWebRuntimeException;
import com.yxsk.relay.job.admin.web.service.AdminJobAppService;
import com.yxsk.relay.job.component.admin.registry.Steward;
import com.yxsk.relay.job.component.common.protocol.message.base.ResultResponse;
import com.yxsk.relay.job.component.common.vo.SlaveInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Author 11376
 * @CreaTime 2019/6/26 20:19
 * @Description
 */
@Controller
@RequestMapping("/admin/quartz/job/app")
public class AdminAppController extends BaseController<JobApps, JobAppsService> {

    @Autowired
    private JobAppController appController;

    @Autowired
    private AdminJobAppService service;

    @Autowired
    private JobAppsService appsService;

    @Autowired
    private Steward steward;

    @GetMapping("")
    public String list(Model model, JobApps jobApps) {
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching().
                withMatcher("title", match -> match.contains());

        jobApps.setDelFlag(BaseEntity.DelFlagEnum.NORMAL.getFlag());

        // 获取角色列表
        Example<JobApps> example = Example.of(jobApps, matcher);
        Page<JobApps> list = this.service.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/system/job/app/index";
    }

    @PostMapping("/ok")
    @ResponseBody
    public ResultResponse ok(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            if (StringUtils.isNotBlank(ids)) {
                String[] idS = ids.split(MULTIPLE_DATA_SEPARATOR);
                if (idS != null) {
                    Stream.of(idS).forEach(id -> this.appController.resume(id));
                }
            }
        }
        return ResultResponse.ok("启用应用成功");
    }

    @PostMapping("/pause")
    @ResponseBody
    public ResultResponse pause(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            if (StringUtils.isNotBlank(ids)) {
                String[] idS = ids.split(MULTIPLE_DATA_SEPARATOR);
                if (idS != null) {
                    Stream.of(idS).forEach(id -> this.appController.pause(id));
                }
            }
        }
        return ResultResponse.ok("暂停应用成功");
    }

    @PostMapping("/delete")
    @ResponseBody
    public ResultResponse delete(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            if (StringUtils.isNotBlank(ids)) {
                String[] idS = ids.split(MULTIPLE_DATA_SEPARATOR);
                if (idS != null) {
                    Stream.of(idS).forEach(id -> this.appController.delete(id));
                }
            }
        }
        return ResultResponse.ok("删除成功");
    }

    @PostMapping("/save")
    @ResponseBody
    @Override
    public ResultResponse save(JobApps jobApps) {
        JobApps apps = this.appsService.findByAppName(jobApps.getAppName());
        if (apps != null && !apps.getId().equals(jobApps.getId())) {
            throw new RelayAdminWebRuntimeException("应用名称重复");
        }
        jobApps.setStatus(JobApps.AppStatus.NORMAL.getStatus());
        return super.save(jobApps);
    }

    @GetMapping("/endpoint/{appName}")
    public String endpoint(@PathVariable("appName") String appName, Model model) {
        List<Steward.SlaveContract> contracts = this.steward.getSlaveContracts(appName);
        List<SlaveInfo> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(contracts)) {
            contracts.stream().forEach(slaveContract -> list.add(slaveContract.getSlave()));
        }
        model.addAttribute("list", list);
        model.addAttribute("entity", this.appsService.findByAppName(appName));
        return getBasicDir() + "/endpoint";
    }

    @Override
    protected String getBasicDir() {
        return "/system/job/app";
    }

}
